package controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.jfinal.aop.Before;
import com.jfinal.core.NotAction;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import db.area;
import db.art;
import db.article;
import db.build;
import db.model;
import db.report;
import utils.FileOpr;
import utils.IResult;
import utils.OptionItem;
import utils.UserInterceptor;
import utils.smartEnv;


//涓存椂娉ㄩ噴鎷︽埅鍣�
@Before(UserInterceptor.class)
public class DataAdminController extends RoleController{
	public DataAdminController(){
		this.setRole(RoleController.DATADMIN);
	}
	
	public void buildnew(@Para("name") String name, @Para("code") String code, @Para("buildstyle") String buildstyle, 
            @Para("buildyear") String buildyear, @Para("builduse") String builduse, 
            @Para("desc") String desc, @Para("proectdesc") String proectdesc, 
            @Para("size") String size, @Para("x") String x, @Para("y") String y, 
            @Para("memo") String memo, @Para("pic") String pic) {

// 创建新的建筑记录 修改于20240726 by FR13NDS
build item = new build();
item.set("name", name)
.set("code", code)
.set("buildstyle", buildstyle)
.set("buildyear", buildyear)
.set("builduse", builduse)
.set("desc", desc)
.set("proectdesc", proectdesc)
.set("size", size)
.set("x", x)
.set("y", y)
.set("memo", memo)
.save();

// 处理上传的图片
if (pic.length() > 0 && !pic.equals("NONEFILE")) {
String sourceFile = smartEnv.fileloc + pic; // 原始文件路径

// 获取建筑记录的 ID
String buildId = item.getStr("id");

// 创建目标路径
String targetDir = smartEnv.fileloc + "gwfcaihua/build/upload/" + buildId;
String targetFileName = "map" + pic.substring(pic.length() - 4); // 文件名

try {
   // 确保目标文件夹存在
   File targetDirectory = new File(targetDir);
   if (!targetDirectory.exists()) {
       targetDirectory.mkdirs(); // 创建文件夹
   }
   
   // 移动文件
   FileOpr.singleFileMove(sourceFile, targetDir, targetFileName);
} catch (Exception e) {
   e.printStackTrace(); // 处理异常
}
}

// 返回成功的 JSON 响应
renderJson(IResult.ok());
}

//	编辑建筑
	public void buildupdate(@Para("id")String id,@Para("name")String name,@Para("code")String code,@Para("buildstyle")String buildstyle,@Para("buildyear")String buildyear,
			@Para("builduse")String builduse,@Para("desc")String desc,@Para("proectdesc")String proectdesc,@Para("size")String size,
			@Para("x")String x,@Para("y")String y,@Para("memo")String memo) {
		build item = build.dao.findById(id);
		if(item != null)
		{
			item.set("name",name).set("code",code).set("buildstyle",buildstyle).set("buildyear",buildyear)
				.set("builduse",builduse).set("desc",desc).set("proectdesc",proectdesc).set("size",size).set("x",x).set("y",y).set("memo",memo).update();
		}else {
			renderJson(IResult.fail("娌℃壘鍒板搴旇褰�"));
			return;
		}
		renderJson(IResult.ok());
	}
//	获取建筑列表
	public void getbuildlist() {
		//寰楀埌鏂囦繚鍗曚綅涓嬬殑鍏ㄩ儴鏂囦繚椤圭洰
		List<build> list = build.dao.find("select * from build");
		renderJson(IResult.ok(list));
	}	
	
	//上传建筑照片
	public void builduploadpic() {
		//涓婁紶鐨勬枃浠讹紝鍏堜繚瀛樺湪涓存椂鏂囦欢涓�, hbim鐨勭紦瀛樻枃浠朵腑
		String upFileName = upImageFile("build\\catch");
		renderJson(IResult.ok(upFileName));
	}
//上传建筑照片
	public void upbuildpic() {
		String upFileName = upImageFile("build\\catch");
		//涓婁紶淇敼鍥剧墖锛屽甫ID鍙傛暟
		String id = getPara("id");
		System.out.println(id);
		String sourceFile = smartEnv.fileloc + upFileName;
		
		String aidSubFileName = "build\\" + id + "\\map.jpg";
		
		String aidPath = smartEnv.fileloc + "build\\" + id;
		String aidName = "map.jpg";
		
		try {
			FileOpr.singleFileMove(sourceFile,aidPath,aidName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(aidSubFileName);
		
		renderJson(IResult.ok(aidSubFileName));
	}
//	删除建筑
	public void builddel(@Para("id")String id) {
		build.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	
	@NotAction
//	获取类型子路径
	public String getTypeSubPath(int type)
	{
		String subPath;
		switch(type) {
		case 1:
			subPath = "pts";
			break;
		case 2:
			subPath = "3mx";
			break;
		case 5:
			subPath = "pic";
			break;
		case 8:
			subPath = "pts";//鍘熷鐐逛簯鏂囦欢
			break;
		case 9:
			subPath = "pic";//鍘熷澶у浘鏂囦欢
			break;
		default:
			return "";
		}
		return subPath;
	}
//	获取个人数据路径
	@NotAction
	public String getPersonDatPath(int type) {
		String strPersonalPath = smartEnv.personloc;
		String subPath = getTypeSubPath(type);
		strPersonalPath = strPersonalPath + subPath;
		
		return strPersonalPath;
	}
//	获取mx
	public void getmxcathlist() {
		//寰楀埌3mx涓存椂鏂囦欢澶逛笅鐨勫垪琛�
		String strPersonalPath = getPersonDatPath(2);
		System.out.println(strPersonalPath);
		if(strPersonalPath == null)
		{
			renderJson(IResult.fail("缂撳啿鏂囦欢澶瑰唴璧勬簮涓虹┖銆�"));
			return;
		}
		
		//鏌ユ壘瀛愭枃浠跺す
	    File  file  =  new  File(strPersonalPath);    
	    if(!file.exists()){    
	           return;    
	    }    
	    if(!file.isDirectory()){    
	           return;    
	    }    
	    String[] tempList = file.list();
	    renderJson(IResult.ok(tempList));
	}
//	获取pts
	public void getptscathlist() {
		//寰楀埌3mx涓存椂鏂囦欢澶逛笅鐨勫垪琛�
		String strPersonalPath = getPersonDatPath(1);
		System.out.println(strPersonalPath);
		if(strPersonalPath == null)
		{
			renderJson(IResult.fail("缂撳啿鏂囦欢澶瑰唴璧勬簮涓虹┖銆�"));
			return;
		}
		
		//鏌ユ壘瀛愭枃浠跺す
	    File  file  =  new  File(strPersonalPath);    
	    if(!file.exists()){    
	           return;    
	    }    
	    if(!file.isDirectory()){    
	           return;    
	    }    
	    String[] tempList = file.list();
	    renderJson(IResult.ok(tempList));
	}
//	设置建筑mx
	public void setbuildmx(@Para("id")String id,@Para("subpath")String subpath) {
		build item = build.dao.findById(id);
		if(item != null) {
			String strPersonalPath = getPersonDatPath(2);

			if(strPersonalPath == null)
				return;
			
			strPersonalPath = strPersonalPath + "\\" + subpath;
			
			System.out.println("strPersonalPath:" + strPersonalPath);
			
			//鐢宠GUID浣滀负鏂扮殑鏂囦欢澶硅矾寰�
			String subTypePath = getTypeSubPath(2);
			//寰楀埌椤圭洰涓嬬殑鏂囦欢澶逛綅缃�
			String strAidSubPath =  UUID.randomUUID().toString().replaceAll("-", "");
			String strAidFullPath = smartEnv.fileloc + subTypePath + "\\" + strAidSubPath;
		
			System.out.println("strPersonalPath:" + strPersonalPath);
			System.out.println("strAidFullPath:" + strAidFullPath);
			
			//绉诲姩鏁版嵁
			try {
				System.out.println("start to move ...");
				Files.move(Paths.get(strPersonalPath), Paths.get(strAidFullPath), StandardCopyOption.REPLACE_EXISTING);
				System.out.println("move ok...");
				
				//鍐欏叆鏁版嵁搴撹矾寰�
				item.set("mxpath",strAidSubPath).update();
				
				renderJson(IResult.ok());
				return;
				
	        } catch (Exception e) {
	        	System.out.println("move error..." + e.getMessage());
	        	System.out.println("move error..." + e.toString());
				
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				renderJson(IResult.fail("璧勬簮绉诲姩澶辫触锛�"));
				return;
			}

		}
		renderJson(IResult.fail("鏌ユ壘瀵瑰簲寤虹瓚鍑洪敊锛�"));
		return;
	}
//	设置建筑pts
	public void setbuildpts(@Para("id")String id,@Para("subpath")String subpath) {
		build item = build.dao.findById(id);
		if(item != null) {
			String strPersonalPath = getPersonDatPath(1);

			if(strPersonalPath == null)
				return;
			
			strPersonalPath = strPersonalPath + "\\" + subpath;
			
			System.out.println("strPersonalPath:" + strPersonalPath);
			
			//鍒ゆ柇缂撳瓨鏂囦欢澶逛腑鐨勭偣浜戞牸寮忥紝鏄痬etadata.json锛屾垨鑰卌loud.js, 
			//鏌ユ壘瀛愭枃浠跺す
			String ptsOldVersionFile = strPersonalPath + "\\cloud.js";
		    File  file  =  new  File(strPersonalPath);   
		    String ptsFileName ="";
		    if(!file.exists()){    
		    	ptsFileName = "\\metadata.json";
		    }else {
		    	ptsFileName = "\\cloud.js";
		    }
			//鐢宠GUID浣滀负鏂扮殑鏂囦欢澶硅矾寰�
			String subTypePath = getTypeSubPath(1);
			//寰楀埌椤圭洰涓嬬殑鏂囦欢澶逛綅缃�
			String strAidSubPath =  UUID.randomUUID().toString().replaceAll("-", "");
			String strAidFullPath = smartEnv.fileloc + subTypePath + "\\" + strAidSubPath;
		
			System.out.println("strPersonalPath:" + strPersonalPath);
			System.out.println("strAidFullPath:" + strAidFullPath);
			
			//绉诲姩鏁版嵁
			try {
				System.out.println("start to move ...");
				Files.move(Paths.get(strPersonalPath), Paths.get(strAidFullPath), StandardCopyOption.REPLACE_EXISTING);
				System.out.println("move ok...");
				
				//鍐欏叆鏁版嵁搴撹矾寰�    杩欓噷鏄惁闇�瑕佷紭鍖栵紝鍒ゆ柇鍓嶅悗鐗堟湰鐨勭偣浜戞牸寮忥紝鎶婃枃浠跺悕鎶撳叆杩涙潵
				item.set("ptspath",strAidSubPath+ptsFileName).update();
				
				renderJson(IResult.ok());
				return;
				
	        } catch (Exception e) {
	        	System.out.println("move error..." + e.getMessage());
	        	System.out.println("move error..." + e.toString());
				
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				renderJson(IResult.fail("璧勬簮绉诲姩澶辫触锛�"));
				return;
			}

		}
		renderJson(IResult.fail("鏌ユ壘瀵瑰簲寤虹瓚鍑洪敊锛�"));
		return;
	}
	
	// 新建区域 修改于2024-7-26 by FR13NDS  已经正确 20240726 晚22：13
	public void areanew() {
	    // 获取参数
	    String name = getPara("name");
	    String buildid = getPara("buildid");

	    // 参数验证
	    if (name == null || name.isEmpty() || buildid == null || buildid.isEmpty()) {
	        renderJson(IResult.error("参数不完整"));
	        return;
	    }

	    // 定义起始值
	    String prefix = buildid + "101";

	    // 查询当前最大 id
	    String maxId = Db.queryStr("SELECT MAX(id) FROM area WHERE id LIKE ?", buildid + "%");

	    String newId;
	    if (maxId != null) {
	        // 提取序号部分并递增
	        try {
	            String sequence = maxId.substring(buildid.length());
	            int newSequence = Integer.parseInt(sequence) + 1;
	            newId = buildid + String.format("%03d", newSequence); // 序号部分补零
	        } catch (NumberFormatException e) {
	            // 处理转换为整数时的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号格式错误"));
	            return;
	        } catch (StringIndexOutOfBoundsException e) {
	            // 处理子字符串超出范围的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号处理出错"));
	            return;
	        }
	    } else {
	        // 如果没有记录，使用起始值作为新的 id
	        newId = prefix;
	    }

	    // 创建并保存数据
	    area item = new area();
	    item.set("id", newId) // 设置生成的 id
	        .set("name", name)
	        .set("buildid", buildid);

	    if (item.save()) {
	        renderJson(IResult.ok());
	    } else {
	        renderJson(IResult.error("保存数据失败"));
	    }
	}




	// 删除区域
	public void delarea() {
		String id  =  getPara("id");
		area.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	//编辑区域
	public void editarea() {
		String id  =  getPara("id");
		String name  =  getPara("name");
		
		area item = area.dao.findById(id);
		if(item != null) {
			item.set("name",name).update();
			renderJson(IResult.ok());
			return;
		}
		renderJson(IResult.fail("鏌ユ壘璁板綍澶辫触锛屼慨鏀瑰け璐ャ��"));
	}
	
	//获取区域列表
	public void getarealist() {
		String buildid  =  getPara("buildid");
		List<area> list = area.dao.find("select * from area where buildid=?",buildid);
		renderJson(IResult.ok(list));
	}
	
	//新建文献
	public void articlenew() {
		String title  =  getPara("title");
		String author  =  getPara("author");
		String keywords  =  getPara("keywords");
		String language  =  getPara("language");
		String type  =  getPara("type");
		String from  =  getPara("from");
		String desc  =  getPara("desc");
		String path  =  getPara("path");
		String memo  =  getPara("memo");
		
		article article = new article();
		article.set("title",title).set("author",author).set("keywords",keywords).set("language",language)
			.set("type",type).set("from",from).set("desc",desc).set("path",path).set("memo",memo).save();
		
		renderJson(IResult.ok());
	}
	
	//上传文献
	public void uploadarticle() {
		//鐩存帴淇濆瓨鍦╝rticle瀛愭枃浠跺す鍐�
		String upFileName = upImageFile("article");
		renderJson(IResult.ok(upFileName));
	}
	
	//删除文献
	public void deletearticle() {
		String id  =  getPara("id");
		article.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	//编辑文献
	public void editarticle() {
		String id  =  getPara("id");
		String title  =  getPara("title");
		String author  =  getPara("author");
		String keywords  =  getPara("keywords");
		String language  =  getPara("language");
		String type  =  getPara("type");
		String from  =  getPara("from");
		String desc  =  getPara("desc");
		String path  =  getPara("path");
		String memo  =  getPara("memo");
		
		article item = article.dao.findById(id);
		if(item != null) {
			item.set("title",title).set("author",author).set("keywords",keywords).set("language",language)
				.set("type",type).set("from",from).set("desc",desc).set("path",path).set("memo",memo).update();
			renderJson(IResult.ok());
			return;
		}
		renderJson(IResult.fail("鏌ユ壘璁板綍澶辫触锛屼慨鏀瑰け璐ャ��"));
	}
	
	//获取文献列表
	public void getarticlelist() {
		List<article> list = article.dao.findAll();
		renderJson(IResult.ok(list));
	}
	
	//上传报告
	public void uploadreport() {
		//鐩存帴淇濆瓨鍦╝rticle瀛愭枃浠跺す鍐�
		String upFileName = upImageFile("report");
		renderJson(IResult.ok(upFileName));
	}
	
	//新建报告
	public void reportnew() {
		String name  =  getPara("name");
		String keywords  =  getPara("keywords");
		String language  =  getPara("language");
		String date  =  getPara("date");
		String desc  =  getPara("desc");
		String memo  =  getPara("memo");
		
		report item = new report();
		item.set("name",name).set("keywords",keywords).set("language",language)
			.set("date",date).set("desc",desc).set("memo",memo).save();
		
		renderJson(IResult.ok());
	}
	//删除报告
	public void delreport() {
		String id  =  getPara("id");
		report.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	//编辑报告
	public void editreport() {
		String id  =  getPara("id");
		String name  =  getPara("name");
		String keywords  =  getPara("keywords");
		String language  =  getPara("language");
		String date  =  getPara("date");
		String desc  =  getPara("desc");
		String path  =  getPara("path");
		String memo  =  getPara("memo");
		
		report item = report.dao.findById(id);
		if(item != null) {
			item.set("name",name).set("keywords",keywords).set("language",language)
			.set("date",date).set("desc",desc).set("path",path).set("memo",memo).update();
			renderJson(IResult.ok());
			return;
		}
		renderJson(IResult.fail("鏌ユ壘璁板綍澶辫触锛屼慨鏀瑰け璐ャ��"));
	}
	
	//获取报告列表
	public void getreportlist() {
		List<report> list = report.dao.findAll();
		renderJson(IResult.ok(list));
	}
	
	//================================================
	//获取模型列表
	public void getmodellist(@Para("areaid")String areaid) {
		List<model> list = model.dao.find("select * from model where areaid = ?",areaid);
		renderJson(IResult.ok(list));
	}
	
	//上传模型  需要修改*************************************
//	public void uploadmodel() {
//		//获取上传的模型
//		UploadFile upfile = getFile();
//		//获取模型路径参数
//		String id = getPara("id");
//		String newPath = smartEnv.fileloc + "model\\" + id;
//		
//		//创建目录
//		File file =new File(newPath);  
//		if  (!file.exists())    
//		{    
//		    file.mkdir();  
//		}
//		
//		// 处理文件名
//		String newFileName = upfile.getFileName();
//		newFileName = "model" + newFileName.substring(newFileName.length()-4);
//		// 构建完整路径
//		String aidFileName = "model\\" + id + "\\" + newFileName;
//		String newfullname;
//		newfullname = newPath + "\\" + newFileName;
//		System.out.println(newfullname);
//		// 重命名并保存模型
//		upfile.getFile().renameTo(new File(newfullname));
//		// 更新数据库记录
//		model item = model.dao.findById(id);
//		if(item != null) {
//			item.set("path",aidFileName).update();
//			renderJson(IResult.ok(aidFileName));
//			return;
//		}
//		renderJson(IResult.fail("娌℃壘鍒版ā鍨嬭褰曘��"));
//	}
	
//	新修改 20240724
	public void uploadmodel() {
	    // 获取上传的模型
	    UploadFile upfile = getFile();
	    // 获取模型路径参数
	    String id = getPara("id");
	    String folderPath = getPara("folderPath"); // 获取前端传递的路径参数，例如 "106/101/101"
	    
	    // 解码 folderPath  这里是将106%2F101%2F101转为106/101/101
	    try {
	        folderPath = URLDecoder.decode(folderPath, StandardCharsets.UTF_8.name());
	    } catch (IOException e) {
	        e.printStackTrace();
	        renderJson(IResult.fail("路径解码失败"));
	        return;
	    }
	    
	    // 构建新的路径
	    String basePath = "D:\\smartfiles\\gwfcaihua";
	    String separator = File.separator;
	    String newPath = basePath + separator + folderPath;
	    
	    // 这里如果前端上传的路径是"106/101/101" 则构建出来的新路径为"D:\\smartfiles\\gwfcaihua\\106\\101\\101"
	    
	    // 创建目录
	    File file = new File(newPath);  
	    if (!file.exists()) {    
	        if (!file.mkdirs()) {
	            renderJson(IResult.fail("创建目录失败"));
	            return;
	        }
	    }
	    
	    // 处理文件名
	    String newFileName = upfile.getFileName();
	    newFileName = "model" + newFileName.substring(newFileName.length() - 4);
	    // 构建完整路径
	    String newFullName = newPath + separator + newFileName;
	    // 这里newFullName 的值应该是 "D:\\smartfiles\\gwfcaihua\\106\\101\\101\\model.rar"
	    
	    // 重命名并保存模型
	    try {
	        Files.move(upfile.getFile().toPath(), Paths.get(newFullName), StandardCopyOption.REPLACE_EXISTING);
	    } catch (IOException e) {
	        e.printStackTrace();
	        renderJson(IResult.fail("文件保存失败"));
	        return;
	    }
	    
	    // 更新数据库记录
	    model item = model.dao.findById(id);
	    if (item != null) {
	        item.set("path", folderPath + separator + newFileName).update();
	        renderJson(IResult.ok(folderPath + separator + newFileName));
	    } else {
	        renderJson(IResult.fail("未找到模型记录"));
	    }
	}

	// 新增模型 修改于2024-7-26 by FR13NDS  已经正确 20240726 晚22：13
	
	public void modelnew() {
	    // 获取参数
	    String name = getPara("name");
	    String buildid = getPara("buildid");
	    String areaid = getPara("areaid");
	    String collecttime = getPara("collecttime");
	    String memo = getPara("memo");

	    // 参数验证
	    if (name == null || name.isEmpty() || buildid == null || buildid.isEmpty() || areaid == null || areaid.isEmpty()) {
	        renderJson(IResult.error("参数不完整"));
	        return;
	    }

	    // 定义 ID 前缀
	    String idPrefix = areaid;

	    // 查询当前最大 ID
	    String maxId = Db.queryStr("SELECT MAX(id) FROM model WHERE id LIKE ?", idPrefix + "%");

	    String newId;
	    if (maxId != null && maxId.length() >= idPrefix.length()) {
	        // 提取序号部分并递增
	        try {
	            String sequence = maxId.substring(idPrefix.length());
	            int newSequence = Integer.parseInt(sequence) + 1;
	            newId = idPrefix + String.format("%03d", newSequence); // 序号部分补零
	        } catch (NumberFormatException e) {
	            // 处理转换为整数时的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号格式错误"));
	            return;
	        } catch (StringIndexOutOfBoundsException e) {
	            // 处理子字符串超出范围的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号处理出错"));
	            return;
	        }
	    } else {
	        // 如果没有记录，序号从101开始
	        newId = idPrefix + "101";
	    }

	    // 创建并保存数据
	    model item = new model();
	    item.set("id", newId) // 设置生成的 id
	        .set("name", name)
	        .set("buildid", buildid)
	        .set("areaid", areaid)
	        .set("collecttime", collecttime)
	        .set("memo", memo);

	    if (item.save()) {
	        renderJson(IResult.ok());
	    } else {
	        renderJson(IResult.error("保存数据失败"));
	    }
	}



	//删除模型
	public void delmodel() {
		String id  =  getPara("id");
		model.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	//编辑模型
	public void editmodel() {
		String id  =  getPara("id");
		String name  =  getPara("name");
		//String buildid  =  getPara("buildid");
		//String areaid  =  getPara("areaid");
		String collecttime  =  getPara("collecttime");
		String memo  =  getPara("memo");
		
		model item = model.dao.findById(id);
		if(item != null) {
			item.set("name",name)
			.set("collecttime",collecttime).set("memo",memo).update();
			renderJson(IResult.ok());
			return;
		}
		renderJson(IResult.fail("鏌ユ壘璁板綍澶辫触锛屼慨鏀瑰け璐ャ��"));
	}
	
	//获取部分树
	public void getparttree() {
		String buildid  =  getPara("buildid");
		List<OptionItem> list = new ArrayList<OptionItem>() ;

		List<Record> listarea = Db.find("select id as value,name as label, buildid as pid from area where buildid=?",buildid);
		List<Record> listmodel = Db.find("select id as value,name as label, areaid as pid from model");

		for(Record itemproject : listarea) {
			OptionItem projectdata = new OptionItem(itemproject.getStr("value"),itemproject.getStr("label"));
			for(Record itembuild : listmodel) {
				if(itemproject.getStr("value").equals(itembuild.getStr("pid"))) {
					OptionItem builddata = new OptionItem(itembuild.getStr("value"),itembuild.getStr("label"));
					projectdata.getChildren().add(builddata);
				}
			}
			list.add(projectdata);
		}
		renderJson(IResult.ok(list));
	}
	
	//获取区域选项 三级联动
	public void getareaoptions() {
		List<OptionItem> list = new ArrayList<OptionItem>() ;
		List<Record> listbuild = Db.find("select id as value,name as label from build");
		List<Record> listarea = Db.find("select id as value,name as label, buildid as pid from area");

		for(Record itemunit : listbuild) {
			OptionItem unitdata = new OptionItem(itemunit.getStr("value"),itemunit.getStr("label"));
			for(Record itemproject : listarea) {
				if(itemunit.getStr("value").equals(itemproject.getStr("pid"))) {
					OptionItem projectdata = new OptionItem(itemproject.getStr("value"),itemproject.getStr("label"));
					unitdata.getChildren().add(projectdata);
				}
			}
			list.add(unitdata);
		}
		
		renderJson(IResult.ok(list));
	}
	//获取部分选项
	public void getpartoptions() {
		List<OptionItem> list = new ArrayList<OptionItem>() ;
		List<Record> listbuild = Db.find("select id as value,name as label from build");
		List<Record> listarea = Db.find("select id as value,name as label, buildid as pid from area");
		List<Record> listmodel = Db.find("select id as value,name as label, areaid as pid from model");

		for(Record itemunit : listbuild) {
			OptionItem unitdata = new OptionItem(itemunit.getStr("value"),itemunit.getStr("label"));
			for(Record itemproject : listarea) {
				if(itemunit.getStr("value").equals(itemproject.getStr("pid"))) {
					OptionItem projectdata = new OptionItem(itemproject.getStr("value"),itemproject.getStr("label"));
					for(Record itembuild : listmodel) {
						if(itemproject.getStr("value").equals(itembuild.getStr("pid"))) {
							OptionItem builddata = new OptionItem(itembuild.getStr("value"),itembuild.getStr("label"));
							projectdata.getChildren().add(builddata);
						}
					}
					unitdata.getChildren().add(projectdata);
				}
			}
			list.add(unitdata);
		}
		
		renderJson(IResult.ok(list));
	}
	
	
	//新建彩画 修改于2024-7-26 by FR13NDS  已经正确 20240726 晚22：13
	public void artnew() {
	    // 获取参数
	    String name = getPara("name");
	    String buildid = getPara("buildid");
	    String areaid = getPara("areaid");
	    String modelid = getPara("modelid");
	    String width = getPara("width");
	    String height = getPara("height");
	    String year = getPara("year");
	    String artstyle = getPara("artstyle");
	    String childstyle = getPara("childstyle");
	    String content = getPara("content");
	    String collecor = getPara("collecor");
	    String collecttime = getPara("collecttime");

	    // 参数验证
	    if (name == null || name.isEmpty() || modelid == null || modelid.isEmpty()) {
	        renderJson(IResult.error("参数不完整"));
	        return;
	    }

	    // 定义 ID 前缀
	    String idPrefix = modelid;

	    // 查询当前最大 ID
	    String maxId = Db.queryStr("SELECT MAX(id) FROM art WHERE id LIKE ?", idPrefix + "%");

	    String newId;
	    if (maxId != null && maxId.length() >= idPrefix.length()) {
	        // 提取序号部分并递增
	        try {
	            String sequence = maxId.substring(idPrefix.length());
	            int newSequence = Integer.parseInt(sequence) + 1;
	            newId = idPrefix + String.format("%03d", newSequence); // 序号部分补零
	        } catch (NumberFormatException e) {
	            // 处理转换为整数时的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号格式错误"));
	            return;
	        } catch (StringIndexOutOfBoundsException e) {
	            // 处理子字符串超出范围的异常
	            e.printStackTrace();
	            renderJson(IResult.error("ID 序号处理出错"));
	            return;
	        }
	    } else {
	        // 如果没有记录，序号从101开始
	        newId = idPrefix + "101";
	    }

	    // 创建并保存数据
	    art item = new art();
	    item.set("id", newId) // 设置生成的 id
	        .set("name", name)
	        .set("buildid", buildid)
	        .set("areaid", areaid)
	        .set("modelid", modelid)
	        .set("width", width)
	        .set("height", height)
	        .set("year", year)
	        .set("artstyle", artstyle)
	        .set("childstyle", childstyle)
	        .set("content", content)
	        .set("collecor", collecor)
	        .set("collecttime", collecttime);

	    if (item.save()) {
	        renderJson(IResult.ok());
	    } else {
	        renderJson(IResult.error("保存数据失败"));
	    }
	}


	//删除彩画
	public void delart() {
		String id  =  getPara("id");
		art.dao.deleteById(id);
		renderJson(IResult.ok());
	}
	
	//编辑彩画
	public void editart() {
		String id  =  getPara("id");
		String name  =  getPara("name");
		String width  =  getPara("width");
		String height  =  getPara("height");
		String year  =  getPara("year");
		String artstyle  =  getPara("artstyle");
		String childstyle  =  getPara("childstyle");
		String content  =  getPara("content");
		String collecor  =  getPara("collecor");
		String collecttime  =  getPara("collecttime");
		
		art item = art.dao.findById(id);
		if(item != null) {
			item.set("name",name).set("width",width).set("height",height)
			.set("year",year).set("artstyle",artstyle).set("childstyle",childstyle)
			.set("content",content).set("collecor",collecor).set("collecttime",collecttime).update();
			renderJson(IResult.ok());
			return;
		}
		renderJson(IResult.fail("鏌ユ壘璁板綍澶辫触锛屼慨鏀瑰け璐ャ��"));
	}
	
	//设置彩画摄像机
	public void setartcam() {
		//鍏堟墽琛実etFile锛岀劧鍚庡啀鑾峰彇鍙傛暟
		String id = getPara("id");
		String cx = getPara("cx");
		String cy = getPara("cy");
		String cz = getPara("cz");
		
		String ux = getPara("ux");
		String uy = getPara("uy");
		String uz = getPara("uz");
		
		String ax = getPara("ax");
		String ay = getPara("ay");
		String az = getPara("az");
		
		art item = art.dao.findFirst("SELECT * FROM art WHERE id=?",id);
		if(item != null) {
			item.set("cx", cx).set("cy", cy).set("cz", cz).set("ux",ux).set("uy", uy).set("uz", uz).set("ax",ax).set("ay", ay).set("az", az).update();
			renderJson(IResult.ok());
		}else {
			renderJson(IResult.fail("淇敼瑙嗗浘澶辫触銆�"));
		}
	}
	//维护彩画检测资料
	public void setarkmark() {
		String id = getPara("id");
		String ismark = getPara("ismark");
		String marks = getPara("marks");
		art item = art.dao.findFirst("SELECT * FROM art WHERE id=?",id);
		if(item != null) {
			item.set("ismark", ismark).set("marks", marks).update();
			renderJson(IResult.ok());
		}else {
			renderJson(IResult.fail("修改视图失败。"));
		}
	}
	
	//获取彩画列表
	public void getartlist(@Para("modelid")String modelid) {
		List<art> list = art.dao.find("select * from art where modelid = ?",modelid);
		renderJson(IResult.ok(list));
	}
	
}
